<template>
  <div id="videoCallDialog" >
    <Modal v-model="modal.show"  :loading="modal.loading" :title="modal.title"  :mask-closable="false"
           :footer-hide=true width="1080px" :closable="false">
      <div style="background-color: #ffffff">
      <Row>
        <Col span="24">
          <div style="display: flex;height:300px">
            <div style="width:45%;height:100%; display: flex;justify-items: center;align-items: center">
              <div v-show="!devicePlay.loading" style="width:100%;height:100%;">
                <video  id="deviceVedioEl" ref="deviceVedioEl" style="width:100%;height:100%" autoplay />
              </div>
              <div v-show="devicePlay.loading" style="width:100%;height:100%;display:flex;
                  justify-content: center;align-items: center">
                  <Spin  size="large" ></Spin>
              </div>
            </div>
            <div style="width:10%;height:100%;display: flex;flex-direction: column;align-items: center;justify-content: center">
              <Button :title="h5.startTheIntercom" type="success" shape="circle" icon="md-call" :disabled="!(!talking && deviceSupport)" @click="starTalk"></Button>
              <br>
              <br>
              <Button :title="h5.endTheIntercom" type="error" shape="circle" icon="md-call"  :disabled="!(talking && deviceSupport)" @click="stopTalk"></Button>
            </div>
            <div style="width:45%;height:100%; ">
              <video v-show="deviceSupport" id="localVedioEl" ref="localVedioEl" style="width:100%;height:100%" autoplay muted/>
              <audio id="localAudioEl" ref="localAudioEl" v-show="1===0" autoplay muted/>
              <div v-show="!deviceSupport" style="width:100%;height:100%;display: flex;justify-content: center;align-items: center;background-color: #0c0c0c">
                <span style="font-size: 30px;color:#8ef8e7;">{{h5.deviceInitFailed}}</span>
              </div>
            </div>
          </div>
        </Col>
      </Row>
      <Row v-show="talking">
        <div style="display: flex;width: 100%;height: 100%;justify-content: center">
          <canvas id="localCanvas" ref="localCanvas" style="width:40%;height:100px;"></canvas>
        </div>
      </Row>
      <Row>
        <Col span="24">
          <div style="display: flex;justify-content: center">
            <Button type="primary" @click="close">{{h5.close}}</Button>
          </div>
        </Col>
      </Row>
      </div>
    </Modal>
  </div>
</template>
<script>
import Device from "@/api/Device";
import MediaDevice from "@/api/MediaDevice";
import {apiResult} from "@/libs/util";
export default {
  computed:{
    h5(){
      return{
        deviceInitFailed:this.$t('device_init_failed'),
        startTheIntercom:this.$t('start_the_intercom'),
        endTheIntercom:this.$t('end_the_intercom'),
        close:this.$t('close'),
      }

    }
  },
  data(){
    return{
      api: new Device(),
      talking: false,
      deviceSupport: true,
      modal:{
        show:false,
        loading:false,
        title:"视频对讲"
      },
      devicePlay:{
        tvRtcPlayer:null,
        tvElement:null,
        loading: true,
      },
      localPlay:{
        localVedioEl:null,
        localCanvas:null,
        audioEl:null,
        audiRtcPlayer:null,
        pushApp:null,
        pushStream:null,
        pushUrl:null,
        mediaStream: null,

      },

      protocol:null,
      playUrl:null,
      deviceId:null,
      channelId:null,
      sourceNode:null,
      analyser:null,
      bufferLength:null,// 初始化缓冲区长度

      audioWaveTimer:null,


      audioCtx:null,
      //waveTimer:timer
    }
  },
  methods:{
    starTalk(){

      const _this = this;
      this.api.playGbTalk(this.deviceId,this.localPlay.pushApp,this.localPlay.pushStream).then((res)=>{
          apiResult(res.data,false,result=>{
            //广播发出成功，可以推流了
            //推流
            _this.localPlay.audiRtcPlayer = new ZLMRTCClient.Endpoint({
              element: _this.localPlay.audioEl,// video 标签
              debug: false,// 是否打印日志
              zlmsdpUrl: _this.localPlay.pushUrl,//流地址
              simulecast: false,
              useCamera: false,
              audioEnable: true,
              videoEnable: false,
              recvOnly: false,
            })
            //音频波形图
            new MediaDevice().audioWave(_this.localPlay.mediaStream,_this.localPlay.localCanvas,
              (res)=>{
                console.log(res);
                _this.audioCtx = res.audioCtx;
                _this.audioWaveTimer = res.timer;
              })
            this.talking = true;
          });
        /*if (res.data.code === 0){
          //广播发出成功，可以推流了
          //推流
          _this.localPlay.audiRtcPlayer = new ZLMRTCClient.Endpoint({
            element: _this.localPlay.audioEl,// video 标签
            debug: false,// 是否打印日志
            zlmsdpUrl: _this.localPlay.pushUrl,//流地址
            simulecast: false,
            useCamera: false,
            audioEnable: true,
            videoEnable: false,
            recvOnly: false,
          })
          //音频波形图
          new MediaDevice().audioWave(_this.localPlay.mediaStream,_this.localPlay.localCanvas,
            (res)=>{
              console.log(res);
              _this.audioCtx = res.audioCtx;
              _this.audioWaveTimer = res.timer;
            })
          this.talking = true;
        }else{
          // 广播失败，关闭窗口
          this.$Message.error(res.data.msg);
        }*/
      })
    },
    stopTalk(){
      if (this.talking){
        if(this.localPlay.audiRtcPlayer){
          this.localPlay.audiRtcPlayer.close();
          this.localPlay.audiRtcPlayer = null;
          if(!!this.localPlay.audioEl){
            this.localPlay.audioEl.srcObject = null;
            this.localPlay.audioEl.load();
          }
        }
        this.api.stopGbTalk(this.deviceId,this.localPlay.pushApp,this.localPlay.pushStream).then((res)=>{
          apiResult(res.data,true,result=>{
            this.$Message.info(this.$t('intercom_stoped'));
          });
        })
        this.talking = false;
        if (!!this.audioCtx){
          this.audioCtx.close();
          this.audioCtx=null;
        }

        if (!!this.audioWaveTimer){
          clearInterval(this.audioWaveTimer)
          this.audioWaveTimer=null;
        }

      }
    },
    openDialog: function (deviceId, channelId) {
      this.stop();
      this.devicePlay.loading=true;
      this.deviceId = deviceId;
      this.channelId = channelId;
      this.modal.show=true;
      this.modal.loading = true;
      this.localPlay.pushApp="live";
      this.localPlay.pushStream = deviceId + "_" + channelId + "_gbtalk";
      let pushUrl = "http://192.168.0.129:8080/index/api/webrtc?app=live&stream=" + this.localPlay.pushStream + "&type=push";
      this.localPlay.pushUrl = this.api.getPushUrl(pushUrl);

      this.getPlayUrl().then(()=>{
        //this.play();

      },(err)=>{
        this.$Message.error(err);
        this.modal.loading = false
      })

      const _this = this;
      const constraints = { audio: true, video: { width: 1280, height: 720 } };
      navigator.mediaDevices.getUserMedia(constraints).then(function(mediaStream) {
        //console.log(">>>>>>>>>> getUserMedia成功！")
        _this.deviceSupport = true;
        _this.localPlay.localVedioEl.srcObject = mediaStream;
        //关闭 MIC使用
        _this.MediaStreamTrack = typeof mediaStream.stop === 'function' ? mediaStream : mediaStream.getTracks()[0];
        _this.localPlay.localVedioEl.play();
        _this.localPlay.mediaStream = mediaStream;
      }).catch((err)=>{
        console.log(">>>>>>>>>> getUserMedia失败 %o！",err);
        _this.$Message.error(this.$t('device_init_failed'));
        _this.deviceSupport = false;
      })

    },
    getPlayUrl(){
      return new Promise((resolve, reject) => {
        this.api.playStart(this.deviceId,this.channelId).then(res=> {
          apiResult(res.data,false,result=>{
            if (!!res.data.data[this.protocol]) {
              const playUrl = res.data.data[this.protocol];
              this.playUrl=this.api.getPlayUrl(playUrl);
              this.playInit();
              resolve()
            }
          });
          /*if (res.data.code === 0) {
            if (!!res.data.data[this.protocol]) {
              const playUrl = res.data.data[this.protocol];
              this.playUrl=this.api.getPlayUrl(playUrl);
              this.playInit();

              //生产环境和开发不一样
/!*              if (process.env.NODE_ENV === "production") {
                //生产环境,通过nginx代理，本地IP:port+/mcpro/webrtc/
                const docUrl = new URL(document.location);
                let originUrl = docUrl.protocol + "//" + docUrl.hostname
                if (!!docUrl.port){
                  originUrl = originUrl + ":" + docUrl.port;
                }
                originUrl = originUrl + "/mcpro/webrtc";
                this.mediaHost = originUrl;
                originUrl = originUrl + playUrl.substring(playUrl.indexOf("/index/api/webrtc?"));
                console.log(">>>>>> 生产环境 播放地址：%o",originUrl);
                this.playUrl = originUrl;
                this.playInit();
              }else{
                //开发环境
                this.playUrl=playUrl.replace(":443/", ":8443/")
                console.log(">>>>>> 开发环境 播放地址：%o",this.playUrl);
                this.playInit();
              }*!/

              resolve()
            }
          }else{
            console.log("!!!!!!!!!错误：%o",res.data.msg);
            console.log("!!!!!!!!!获取播放地址错误，请确认设备是否在线");
          }*/
        }).catch(err => {
          reject(err)
        })
      });
    },
    playInit(){
      this.devicePlay.tvRtcPlayer = null;
      const _this = this;
      this.devicePlay.tvRtcPlayer = new ZLMRTCClient.Endpoint({
        element: this.devicePlay.tvElement,// video 标签
        debug: false,// 是否打印日志
        zlmsdpUrl: _this.playUrl,//流地址
        simulecast: true,
        useCamera: true,
        audioEnable: true,
        videoEnable: true,
        recvOnly: true,
      })
      //console.log(">>>>>> audioPlayer:%o",this.devicePlay.tvRtcPlayer);
      //协商出错
      this.devicePlay.tvRtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR,(e)=>{// ICE 协商出错
        console.error('!!!!!!!!! ICE 协商出错: %o',e)
      });

      //播放成功
      this.devicePlay.tvRtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_REMOTE_STREAMS,(e)=>{//获取到了远端流，可以播放
        console.log('播放成功: %o',e);
        this.devicePlay.loading=false;
      });

      //交换失败
      this.devicePlay.tvRtcPlayer.on(ZLMRTCClient.Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED,(e)=>{// offer anwser 交换失败
        console.error('!!!!!!!!!  offer anwser 交换失败: %o',e)
      });
      //当前状态==>
      this.devicePlay.tvRtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_CONNECTION_STATE_CHANGE,function(state)
      {// RTC 状态变化 ,详情参考 https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionState
        console.log('********* 当前状态==>',state)
      });

      //rtc datachannel 打开
      this.devicePlay.tvRtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_OPEN,function(event)
      {
        console.log('rtc datachannel 打开 :',event)
      });

      //rtc datachannel 消息
      this.devicePlay.tvRtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_MSG,function(event)
      {
        console.log('rtc datachannel 消息 :',event.data)
        document.getElementById('msgrecv').value = event.data
      });
      //rtc datachannel 错误
      this.devicePlay.tvRtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_ERR,function(event)
      {
        console.log('rtc datachannel 错误 :',event)
      });
      //rtc datachannel 关闭
      this.devicePlay.tvRtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_CLOSE,function(event)
      {
        console.log('rtc datachannel 关闭 :',event)
      });
    },
    close: function(){
      this.stop();
      this.modal.show = false;
    },
    stop(){
      if(!!this.devicePlay.tvRtcPlayer)
      {
        this.devicePlay.tvRtcPlayer.close();
        this.devicePlay.tvRtcPlayer = null;
        this.devicePlay.tvElement = this.$refs.deviceVedioEl;
        if(!!this.devicePlay.tvElement)
        {
          this.devicePlay.tvElement.srcObject = null;
          this.devicePlay.tvElement.load();
        }
      }
      this.stopTalk();
      this.MediaStreamTrack && this.MediaStreamTrack.stop();
    },

  },
  mounted() {
    this.modal.title = this.$t('video_call')
    const _this = this;
    const isHttps = 'https:' === document.location.protocol;
    this.protocol = isHttps?"rtcs":"rtc";
    this.$nextTick(()=>{
      this.devicePlay.tvElement = this.$refs.deviceVedioEl;
      this.localPlay.localVedioEl = this.$refs.localVedioEl;
      this.localPlay.localCanvas = this.$refs.localCanvas;
      this.localPlay.audioEl = this.$refs.localAudioEl;
    });

  }
}
</script>
<style lang="less">
  @import "../.././template";
</style>
